import { defineStore } from 'pinia';

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [],
  }),
  getters: {
    totalPrice: (state) => {
        console.log("计算总价")
        return state.items.reduce((total, item) => {
            return total + item.price * item.quantity
        }, 0)
    },
  },
  actions: {
    addItem(item) {
      const existingItem = this.items.find(i => i.id === item.id);
      if (existingItem) {
        existingItem.quantity += item.quantity;
      } else {
        this.items.push(item);
      }
    },
    removeItem(id) {
      const index = this.items.findIndex(i => i.id === id);
      if (index > -1) {
        this.items.splice(index, 1);
      }
    },
    updateItemQuantity(id, quantity) {
        const item = this.items.find(i => i.id === id);
        if (item) {
          console.log("修改数量")
          item.quantity = quantity;
        }
      },
  },
});
